package product.portal.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import product.portal.util.callback.settings.SettingAction;
import product.portal.util.callback.settings.SettingCallbackFactory;
import product.portal.util.log.ILogger;
import product.portal.util.log.LogModule;
import product.portal.util.log.LogUtil;

/**
 * java shell命令工具类 
 * javac JavaShellUtil.java -encoding utf-8
 */
public class JavaShellUtil {
	
	private static ILogger logger = LogUtil.getLogger(LogModule.Util, JavaShellUtil.class);

	public static String lineseparator = System.getProperty("line.separator");
	public static String COMMAND_SH = "sh";
	public static String COMMAND_EXIT = "exit\n";
	public static String COMMAND_LINE_END = "\n";

	static {
		if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			logger.info("window");
			COMMAND_SH = "cmd";
		} else {
			logger.info("unix");
		}
	}

	public static CommandResult execCommand(String command) {
		return execCommand(new String[] { command }, true);
	}

	public static CommandResult execCommand(String command, boolean isNeedResultMsg) {
		return execCommand(new String[] { command }, isNeedResultMsg);
	}

	public static CommandResult execCommand(List<String> commands, boolean isNeedResultMsg) {
		return execCommand(commands == null ? null : commands.toArray(new String[] {}), isNeedResultMsg);
	}

	/**
	 * execute shell commands {@link CommandResult#result} is -1, there maybe some
	 * excepiton.
	 *
	 * @param commands     command array
	 * @param needResponse whether need result msg
	 */
	public static CommandResult execCommand(String[] commands, final boolean needResponse) {
		int result = -1;
		if (commands == null || commands.length == 0) {
			return new CommandResult(result, null, "空命令");
		}

		Process process = null;

		final StringBuilder successMsg = new StringBuilder();
		final StringBuilder errorMsg = new StringBuilder();

		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec(COMMAND_SH);
			os = new DataOutputStream(process.getOutputStream());
			for (String command : commands) {
				if (command == null) {
					continue;
				}
				// donnot use os.writeBytes(commmand), avoid chinese charset error
				os.write(command.getBytes());
				os.writeBytes(COMMAND_LINE_END);
				os.flush();
			}
			os.writeBytes(COMMAND_EXIT);
			os.flush();
			String encoding = System.getProperty("sun.jnu.encoding");
			final BufferedReader successResult = new BufferedReader(new InputStreamReader(process.getInputStream(), encoding));
			final BufferedReader errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream(), encoding));

			// 此处会写文档
			new Thread(new Runnable() {
				public void run() {
					try {
						if (needResponse) {
							String line;
							while ((line = successResult.readLine()) != null) {
								successMsg.append(line);
								successMsg.append(lineseparator);
								SettingCallbackFactory.notifyListeners(SettingAction.BandwidthServer, successMsg.toString());
								logger.info("executeShellWithResultAsync server message:" + successMsg.toString());
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
			// 启动两个线程,解决process.waitFor()阻塞问题
			new Thread(new Runnable() {
				public void run() {
					try {
						if (needResponse) {
							String line;
							while ((line = errorResult.readLine()) != null) {
								errorMsg.append(line);
								errorMsg.append(lineseparator);
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
			result = process.waitFor();
			if (errorResult != null) {
				errorResult.close();
			}
			if (successResult != null) {
				successResult.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (process != null) {
					process.destroy();
				}
			}

		}
		return new CommandResult(result, successMsg == null ? null : successMsg.toString(),
				errorMsg == null ? null : errorMsg.toString());
	}

	public static class CommandResult {

		public int result;
		public String responseMsg;
		public String errorMsg;

		public CommandResult(int result) {
			this.result = result;
		}

		public CommandResult(int result, String responseMsg, String errorMsg) {
			this.result = result;
			this.responseMsg = responseMsg;
			this.errorMsg = errorMsg;
		}

		@Override
		public String toString() {
			return "CommandResult{" + "errorMsg='" + errorMsg + '\'' + ", result=" + result + ", responseMsg='"
					+ responseMsg + '\'' + '}';
		}
	}
}